<?php

namespace app\admin\controller\wechat;


use app\admin\controller\Base;
use think\facade\Request;
use think\facade\View;
use think\facade\Db;
use app\common\model\Wechat as WechatModel;
use helper\Wechat as WechatClass;
use EasyWeChat\Factory;
use think\Paginator;


class Wxmaterial extends Base
{
	public function initialize()
    {
        parent::initialize(); 
        $map[] = ['status','=',1];
        $wx = WechatModel::where($map)->find();
        $this->Wechat = new WechatClass($wx['domain']);
        $this->app = Factory::officialAccount($this->Wechat->get_config());
        
        $this->wechatConfig = WechatModel::loadList([],100);
        View::assign('wechat',$this->wechatConfig['list']);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $page = $this->request->get('page')?$this->request->get('page'):1;
        $limit = $this->request->get('limit')?$this->request->get('limit'):10;
        // print_r($this->wechatConfig);die;
        $wechat_id = $this->request->get('wx_id')?$this->request->get('wx_id'):$this->wechatConfig['list'][0]['id'];
        $arr = Db::name('wx_news')->where('wx_id',$wechat_id)->order('id desc')->paginate(array('list_rows'=> $limit,'page'=>$page))->each(function($item, $key){
            $item['child'] = Db::name('wx_news_article')->where('id','in',$item['article_id'])->limit(7)->select()->toArray();
            return $item;
        });
        $parmas = request()->param();
        $paginator = $arr->appends($parmas)->render();
        $list = $arr->toArray();
        // print_r($list);die;
        View::assign('lists',$list['data']);
        View::assign('paginator',$paginator);
        return view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            $wx_id = $data[0]['wx_id'];
            $ids = '';
            foreach ($data as $key => $value) {
                $ids .= Db::name('wx_news_article')->insertGetId($value).',';
            }
            $res = Db::name('wx_news')->insert(['wx_id'=>$wx_id,'article_id'=>$ids,'create_time'=>date('Y-m-d H:i:s')]);
            if ($res) {
                $this->success('添加成功',url('index'));
            }else{
                $this->error('添加失败');
            }
        }else{
            return view();
        }
    }


    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            $json_data = json_decode($data['json'],true);
            $wx_id = $json_data[0]['wx_id'];
            $ids = '';
            foreach ($json_data as $key => $value) {
                $res = Db::name('wx_news_article')->where('id',$value['id'])->find();
                if ($res) {
                    $ids .= $value['id'].',';
                    Db::name('wx_news_article')->where('id',$value['id'])->update($value);
                }else{
                    $ids .= Db::name('wx_news_article')->insertGetId($value).',';
                }
                
            }
            $res = Db::name('wx_news')->where('id',$data['news_id'])->update(['wx_id'=>$wx_id,'article_id'=>$ids,'create_time'=>date('Y-m-d H:i:s')]);
            
            if ($res !== false) {
                $this->success('保存成功',url('index'));
            }else{
                $this->error('保存失败');
            }
        }else{
            $id = $this->request->get('id');
            $info = Db::name('wx_news')->where('id',$id)->find();
            $info['child'] = Db::name('wx_news_article')->where('id','in',$info['article_id'])->limit(7)->select()->toArray();
            $view = [
                'info' => $info,
            ];
            View::assign($view);
            return view();
        }
    }
    public function delart($id)
    {
        $id = $this->request->get('id');
        $res = Db::name('wx_news_article')->where('id',$id)->delete();
        if ($res) {
            $this->success('删除成功',url('index'));die;
        }else{
            $this->error('删除失败');die;
        }
    }
    public function del()
    {
        $id = $this->request->get('id');
        $article_id = Db::name('wx_news')->field('article_id')->where('id',$id)->find();
        Db::startTrans();
        try {
            Db::name('wx_news_article')->where('id','in',$article_id)->delete();
            Db::name('wx_news')->where('id',$id)->delete();
            // 提交事务
            Db::commit();
            $this->success('删除成功',url('index'));die;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('删除失败'.$e->getMessage());die;
        }
    }

    public function getlist()
    {
        
        $wx_id = $this->request->get('wx_id');
        if (!$wx_id) {
            throw new \think\Exception('非法参数');
        }
        $page = $this->request->get('page')?$this->request->get('page'):1;
        $limit = $this->request->get('limit')?$this->request->get('limit'):10;
        // print_r($this->wechatConfig);die;
        $arr = Db::name('wx_news')->where('wx_id',$wx_id)->order('id desc')->paginate(array('list_rows'=> $limit,'page'=>$page))->each(function($item, $key){
            $item['child'] = Db::name('wx_news_article')->where('id','in',$item['article_id'])->limit(7)->select()->toArray();
            return $item;
        });
        $parmas = request()->param();
        $paginator = $arr->appends($parmas)->render();
        $list = $arr->toArray();
        // print_r($list);die;
        View::assign('lists',$list['data']);
        View::assign('paginator',$paginator);
        return view();
        
    }
}
